package cn.imnu.lowcodeformgeneratorbackend.controller;

import cn.imnu.lowcodeformgeneratorbackend.dto.auth.LoginRequest;
import cn.imnu.lowcodeformgeneratorbackend.dto.auth.RegisterRequest;
import cn.imnu.lowcodeformgeneratorbackend.dto.auth.UserResponse;
import cn.imnu.lowcodeformgeneratorbackend.service.UserService;
import cn.imnu.lowcodeformgeneratorbackend.util.JwtUtil;
import cn.imnu.lowcodeformgeneratorbackend.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin
@Tag(name = "用户认证接口")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录获取token")
    public Result<String> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest);
            return Result.success("登录成功", token);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册")
    public Result<UserResponse> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            UserResponse userResponse = userService.register(registerRequest);
            return Result.success("注册成功", userResponse);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/userinfo")
    @Operation(summary = "获取用户信息", description = "获取当前登录用户的详细信息")
    @SecurityRequirement(name = "Authorization")
    public Result<UserResponse> getUserInfo(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "未授权");
            }

            token = token.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error(401, "token无效");
            }

            UserResponse userResponse = userService.getUserInfo(userId);
            return Result.success(userResponse);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/logout")
    @Operation(summary = "用户退出", description = "用户退出登录")
    @SecurityRequirement(name = "Authorization")
    public Result<String> logout() {
        // JWT是无状态的，客户端删除token即可
        return Result.success("退出成功", null);
    }
}